import CryptoJS from 'crypto-js';

var _querystring: { [key: string]:any} = {};
export const querystring = () => {
  window.location.search
      .substr(1)
      .split('&')
      .map(item => {
        const items = item.split('=');
        _querystring[items[0]] = decodeURIComponent(items[1]);
      });

  return _querystring;
};

export const curQueryString = () => {
    let obj: {[key:string]:any} = {}
    window.location.search
      .substr(1)
      .split('&')
      .map(item => {
        const items = item.split('=');
        obj[items[0]] = decodeURIComponent(items[1]);
      });

  return obj;
}


function getRandomCode(length = 12) {
  if (length > 0) {
    var data = [
      '0',
      '1',
      '2',
      '3',
      '4',
      '5',
      '6',
      '7',
      '8',
      '9',
      'A',
      'B',
      'C',
      'D',
      'E',
      'F',
      'G',
      'H',
      'I',
      'J',
      'K',
      'L',
      'M',
      'N',
      'O',
      'P',
      'Q',
      'R',
      'S',
      'T',
      'U',
      'V',
      'W',
      'X',
      'Y',
      'Z',
      'a',
      'b',
      'c',
      'd',
      'e',
      'f',
      'g',
      'h',
      'i',
      'j',
      'k',
      'l',
      'm',
      'n',
      'o',
      'p',
      'q',
      'r',
      's',
      't',
      'u',
      'v',
      'w',
      'x',
      'y',
      'z'
    ];
    var nums = '';
    for (var i = 0; i < length; i++) {
      var r = parseInt(''+Math.random() * 61);
      nums += data[r];
    }
    return nums;
  } else {
    return false;
  }
}

/**
 * @description 获取签名
 * @param {String} method  'GET POST'
 * @param {String} api
 */
export const parseParams = (data: {[key:string]:any}) => {
    try {
      var tempArr = [];
      for (var i in data) {
        var key = encodeURIComponent(i);
        var value = encodeURIComponent(data[i]);
        tempArr.push(key + '=' + value);
      }
      var urlParamsStr = tempArr.join('&');
      return urlParamsStr;
    } catch (err) {
      return '';
    }
  };
export function getSignAll(method:string, api:string) {
  let { authKey = '', accessToken = '' } = querystring();
  let nonce = getRandomCode(),
    timestamp = parseInt(''+new Date().getTime() / 1000),
    message = `${method + api}?accessToken=${accessToken}&nonce=${nonce}&timestamp=${timestamp}`,
    sign = CryptoJS.HmacSHA1(message, authKey).toString(CryptoJS.enc.Hex);
    let resObj: {[key:string]:any} = {
    nonce: nonce,
    timestamp: timestamp,
    sign: sign
  }
  if(api.indexOf('v4') > -1){
    resObj['authKey'] = authKey;
  }else{
    resObj['auth_key'] = authKey;
  }
  return resObj;
}
